package com.cn.customer.housekeeping.housekeepingb.ui;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.cn.customer.housekeeping.housekeepingb.R;
import com.cn.customer.housekeeping.housekeepingb.bean.BaseResp;
import com.cn.customer.housekeeping.housekeepingb.biz.personcenter.IUserLoginView;
import com.cn.customer.housekeeping.housekeepingb.biz.personcenter.InterfacePresenter;
import com.cn.customer.housekeeping.housekeepingb.bridge.BridgeFactory;
import com.cn.customer.housekeeping.housekeepingb.bridge.Bridges;
import com.cn.customer.housekeeping.housekeepingb.bridge.cache.sharePref.EBSharedPrefManager;
import com.cn.customer.housekeeping.housekeepingb.bridge.cache.sharePref.EBSharedPrefUser;
import com.cn.customer.housekeeping.housekeepingb.citypicker.utils.StringUtils;
import com.cn.customer.housekeeping.housekeepingb.util.DialogUtil;
import com.cn.customer.housekeeping.housekeepingb.util.NavUtils;
import com.cn.customer.housekeeping.housekeepingb.util.Utils;

import java.util.ArrayList;
import java.util.List;


/***
 * 启动页
 */
public class SplashActivity extends Activity implements IUserLoginView, AMap.OnMyLocationChangeListener ,PoiSearch.OnPoiSearchListener{
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private static final int PERMISSON_REQUESTCODE = 0;
    private static final int sleepTime = 2000;
    private Dialog mPermissionsDialog;
    private Dialog mApkDlg;
    private boolean isNeedCheck = true;
    private InterfacePresenter mInterfacePresenter;
    EBSharedPrefManager manager = BridgeFactory.getBridge(Bridges.SHARED_PREFERENCE);
    protected String[] needPermissions = {
//            Manifest.permission.ACCESS_COARSE_LOCATION,
//            Manifest.permission.ACCESS_FINE_LOCATION,
//            Manifest.permission.ACCESS_WIFI_STATE,
//            Manifest.permission.CHANGE_WIFI_STATE,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE,
//            Manifest.permission.READ_EXTERNAL_STORAGE,
//            Manifest.permission.READ_PHONE_STATE,
//            Manifest.permission.RECORD_AUDIO,
//            Manifest.permission.CAMERA,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE,//存储卡写入权限
//            Manifest.permission.READ_EXTERNAL_STORAGE,//存储卡读取权限
//            Manifest.permission.READ_CONTACTS,//读联系人权限
//            Manifest.permission.READ_PHONE_STATE,
//            Manifest.permission.ACCESS_WIFI_STATE,
//            Manifest.permission.ACCESS_NETWORK_STATE,
//            Manifest.permission.VIBRATE,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_splash);
        mInterfacePresenter = new InterfacePresenter();
        mInterfacePresenter.attachView(this);

    }




    @Override
    public void onError(BaseResp s) {

    }

    @Override
    public void onSuccess(BaseResp s) {

    }


    public void finishs() {
//        NavUtils.gotoLoginPasswordActivity(SplashActivity.this);
        NavUtils.gotoTabMainActivity(SplashActivity.this);
        finish();
//        if (manager.getKDPreferenceUserInfo().getBoolean(EBSharedPrefUser.isLand, false)) {
//            NavUtils.gotoMainActivity(SplashActivity.this);
//            finish();
//        } else {
//            String phone = manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.phone, "");
//            if (TextUtils.isEmpty(phone)) {
////                NavUtils.gotoLoginCodeActivity(SplashActivity.this);
//                NavUtils.gotoLoginPasswordActivity(SplashActivity.this);
//            } else {
//                NavUtils.gotoLoginCodeAgainActivity(SplashActivity.this);
//            }
//            finish();
//        }

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }
    private List<String> findDeniedPermissions(Activity activity, String... permissions){
        List<String> deniedPermissions = new ArrayList<>();
        for (String permission : permissions){
            if (ActivityCompat.checkSelfPermission(activity, permission)
                    != PackageManager.PERMISSION_GRANTED){
                deniedPermissions.add(permission);
            }
        }
        return deniedPermissions;
    }
    private static final int REQUEST_CODE = 2333;
    @Override
    protected void onResume() {
        super.onResume();
//
//        if (isNeedCheck) {
//            if (Utils.checkPermissions(this, needPermissions)) {
//                startCountDownTime(3);
//            } else {
//
//            }
//
//        }
        List<String> deniedPermissions = findDeniedPermissions(this, needPermissions);
        if (!deniedPermissions.isEmpty()){
            ActivityCompat.requestPermissions(this, needPermissions, REQUEST_CODE);
        }else{
            //所有权限都已经同意了
            initLocation();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

//        if (requestCode == PERMISSON_REQUESTCODE) {
//            if (!Utils.verifyPermissions(paramArrayOfInt)) {
//                isNeedCheck = false;
//                showPermissionsDialog();
//            } else {
//            }
//        }
        switch (requestCode){
            case REQUEST_CODE:
                List<String> deniedPermissions = new ArrayList<>();
                int length = grantResults.length;
                for (int i = 0; i < length; i++){
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED){
                        //该权限被拒绝了
                        deniedPermissions.add(permissions[i]);
                    }
                }
                if (deniedPermissions.size() > 0){
//                    mListener.onDenied(deniedPermissions);
                    showPermissionsDialog();
                }else{
//                    mListener.onGranted();
                    initLocation();
                }
                break;
            default:
                break;
        }
    }


    private void showPermissionsDialog() {
        if (mPermissionsDialog == null) {
            mPermissionsDialog = DialogUtil.showMessageDialog(this,
                    null,
                    "请添加必要权限",
                    "取消",
                    "设置",
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mPermissionsDialog.dismiss();
                            finish();
                        }
                    },
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mPermissionsDialog.dismiss();
                            NavUtils.startAppSettings(SplashActivity.this);
                            isNeedCheck = true;
                        }
                    });
        }
        mPermissionsDialog.show();
    }


    private void initLocation() {
        locationClient = new AMapLocationClient(this.getApplicationContext());
        locationOption = getDefaultOption();
        locationClient.setLocationOption(locationOption);
        locationClient.setLocationListener(locationListener);
        locationClient.startLocation();
    }

    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//Battery_Saving
        mOption.setGpsFirst(false);
        mOption.setHttpTimeOut(30000);
        mOption.setInterval(2000);
        mOption.setNeedAddress(true);
        mOption.setOnceLocation(true);//是否单次定位
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {

                StringBuffer sb = new StringBuffer();
                if (location.getErrorCode() == 0) {
                    sb.append("定位成功" + "");
                    sb.append("定位类型: " + location.getLocationType() + "");
                    sb.append("经    度    : " + location.getLongitude() + "");
                    sb.append("纬    度    : " + location.getLatitude() + "");
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "");
                    sb.append("提供者    : " + location.getProvider() + "");

                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "");
                    sb.append("角    度    : " + location.getBearing() + "");
                    // 获取当前提供定位服务的卫星个数
                    sb.append("星    数    : " + location.getSatellites() + "");
                    sb.append("国    家    : " + location.getCountry() + "");
                    sb.append("省            : " + location.getProvince() + "");
                    sb.append("市            : " + location.getCity() + "");
                    sb.append("城市编码 : " + location.getCityCode() + "");
                    sb.append("区            : " + location.getDistrict() + "");
                    sb.append("区域 码   : " + location.getAdCode() + "");
                    sb.append("地    址    : " + location.getAddress() + "");
                    sb.append("兴趣点    : " + location.getPoiName() + "");
                    //定位完成的时间
                    sb.append("定位时间: " + Utils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "");
                    EBSharedPrefManager manager = BridgeFactory.getBridge(Bridges.SHARED_PREFERENCE);
                    manager.getKDPreferenceUserInfo().saveString(EBSharedPrefUser.lat, location.getLatitude() + "");
                    manager.getKDPreferenceUserInfo().saveString(EBSharedPrefUser.lon, location.getLongitude() + "");
                    manager.getKDPreferenceUserInfo().saveString(EBSharedPrefUser.citycode, location.getCityCode() + "");
                    manager.getKDPreferenceUserInfo().saveString(EBSharedPrefUser.city,   StringUtils.extractLocation(location.getCity(),location. getDistrict()) + "");
                    manager.getKDPreferenceUserInfo().saveString(EBSharedPrefUser.getAoiName, location.getAoiName() + "");

                    LatLonPoint latLonPoint = new LatLonPoint(location.getLatitude(), location.getLongitude());
                    doSearchQuery(latLonPoint);

                } else {
                    //定位失败
                    sb.append("定位失败" + "");
                    sb.append("错误码:" + location.getErrorCode() + "");
                    sb.append("错误信息:" + location.getErrorInfo() + "");
                    sb.append("错误描述:" + location.getLocationDetail() + "");
                }
                //定位之后的回调时间
                sb.append("回调时间: " + Utils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");

                String result = sb.toString();
                System.out.println("wjm===" + result);

            } else {

            }
        }
    };

    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;
    private List<PoiItem> poiItems;// poi数据
    private int currentPage = 0;// 当前页面，从0开始计数
    private PoiResult poiResult; // poi返回的结果
    protected void doSearchQuery(LatLonPoint latLonPoint) {
        String keyWord = "楼栋号";
        currentPage = 0;
        query = new PoiSearch.Query(keyWord, "楼栋号", manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.city, ""));// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页

        if (latLonPoint != null) {
            poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(this);
            poiSearch.setBound(new PoiSearch.SearchBound(latLonPoint, 5000, true));//
            // 设置搜索区域为以lp点为圆心，其周围5000米范围
            poiSearch.searchPOIAsyn();// 异步搜索
        }
    }
    private void destroyLocation() {
        if (null != locationClient) {
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
    }

    @Override
    public void onMyLocationChange(Location location) {

    }


    @Override
    public void onPoiSearched(PoiResult result, int rcode) {
        if (rcode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    List<SuggestionCity> suggestionCities = poiResult
                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                    if (poiItems != null && poiItems.size() > 0) {
                        manager.getKDPreferenceUserInfo().saveString(EBSharedPrefUser.lat, poiItems.get(0).getLatLonPoint().getLatitude() + "");
                        manager.getKDPreferenceUserInfo().saveString(EBSharedPrefUser.lon,poiItems.get(0).getLatLonPoint().getLongitude() + "");
                        manager.getKDPreferenceUserInfo().saveString(EBSharedPrefUser.getAoiName,poiItems.get(0).getTitle() + "");
                    } else {

                    }
                }
            } else {

            }
        } else {

        }
        finishs();
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }
}
